﻿using System.Transactions;
using AutoMapper;
using MediatR;
using Provenance.Domain.User;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.User;
using Provenance.Write.Api.Application.Command.User;

namespace Provenance.Write.Api.Application.CommandHandler.User
{
    public class InsertUserCommandHandler : IRequestHandler<InsertUserCommand, ApiResult>
    {
        private readonly IUserInfoRepository _userInfoRepository;
        private readonly IUserRoleRepository _userRoleRepository;
        private readonly ILogger<InsertUserCommandHandler> _logger;
        private readonly IMapper _mapper;
        public InsertUserCommandHandler(IUserInfoRepository userInfoRepository, IUserRoleRepository userRoleRepository, ILogger<InsertUserCommandHandler> logger, IMapper mapper)
        {
            _userInfoRepository = userInfoRepository;
            _userRoleRepository = userRoleRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult> Handle(InsertUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        var user = _mapper.Map<UserInfo>(request);
                        await _userInfoRepository.InsertEntity(user);

                        string[] stringIds = request.RoleIds.Split(',');
                        int[] IntIds = stringIds.Select(x => int.Parse(x)).ToArray();
                        var userRoleList = new List<UserRole>();
                        foreach (var id in IntIds)
                        {
                            userRoleList.Add(new UserRole()
                            {
                                UserId = user.UserId,
                                RoleId = id
                            });
                        }
                        await _userRoleRepository.InsertRangeEntity(userRoleList);
                        tran.Complete();
                        return ApiResult.Success();
                    }
                    finally
                    {
                        tran.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in InsertUserCommandHandler.Handle" + ex.Message);
                return ApiResult.Failure(ex.Message);
            }
        }


    }
}
